import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';

@Injectable({
  providedIn: 'root'
})
export class ExportExcelService {

  constructor() { }


  /**
   * 功能：传入数据直接导出
   * @param data 二维数组
   * @param fileName 导出的文件名
   */
  export (data: any[][], fileName?: string) {
    /* generate worksheet */
    const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(data);

    /* generate workbook and add the worksheet */
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    fileName = fileName || 'export';
    XLSX.writeFile(wb, `${fileName}.xlsx`);
  }

  /**
   * 功能根据传入的数据，处理成可以导出的格式，然后导出
   * @param titleList 导出XLS的列头字段
   * @param rowData 导出的明细数据（Grid行数据）
   * @param fileName 导出的文件名
   */
  exportWithDealData(titleList: any[], rowData: any[], fileName?: string) {
    const exportData = [];
    const headTitle = [];
    const gridHeaderList = [];

    /* step 1： 获取头部的信息 */
    for (let i = 0, len = titleList.length; i < len; i++) {
      // 拼接头部信息
      const temp = {};
      temp['field'] = titleList[i]['field'];
      temp['title'] = titleList[i]['headerName'];
      gridHeaderList.push(temp);

      // 拼接 excel 头部字段列表
      headTitle.push(titleList[i]['headerName']);
    }
    exportData.push(headTitle);

    /* step 2: 根据 step 1 的信息，拼接 XLS 数组*/
    for (let i = 0, len = rowData.length; i < len; i++) {
      const tempList = [];
      const temp = rowData[i];
      for (let j = 0, length = gridHeaderList.length; j < length; j++) {
        const key = gridHeaderList[j]['field'];
        tempList.push( temp[key] !== null && temp[key] !== undefined ? temp[key] : '');
      }
      exportData.push(tempList);
    }

    /* exprot Data */
    this.export(exportData, fileName);
  }

}
